package com.thread.chapter2;

import cn.hutool.core.thread.ThreadUtil;
import lombok.Data;

@Data
public class Demo233 extends Thread {

    private boolean isRunning = true;

    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean running) {
        isRunning = running;
    }

    @Override
    public void run() {
        super.run();
        System.out.println("进入run");
        while (isRunning == true) {
            //只有在对变量读取频率很高的情况下，虚拟机才不会及时写回到主内存，而当频率没有达到虚拟机认为的高频率时，普通变量和volatile是同样的处理逻辑
            //去掉sleep则线程永远不会停止,isRunning一直是true,加了sleep后会获取到isRunning的新值false
            //去掉sleep想让线程停止的话就将isRunning设置为volatile,强制从公共内存中获取变量
            ThreadUtil.sleep(100);
        }
        System.out.println("线程被停止了");
    }

    public static void main(String[] args) {

        Demo233 thread = new Demo233();
        thread.start();
        ThreadUtil.sleep(2000);
        thread.setRunning(false);
        System.out.println("已经赋值为false");
        System.out.println(new Demo233().isRunning());
    }
}
